<?php
/**
 * 文章模块
 * User: 1874
 * Date: 2019/8/1
 * Time: 21:00
 */

namespace app\adminplatform\controller;

use app\adminplatform\model\Log;
use app\adminplatform\model\AuthGroup;
use app\adminplatform\model\ArticleClassify;
use app\adminplatform\model\Article as ArticleModel;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\facade\Session;

class Article extends Initial {
    /*
     * 文章列表
     */
    public function articleList(){
        $map = [];
        if(input('name')) $map[] = ['ar_title','like','%'.input('name').'%']; //名称
        if(input('classifyId')) {   //分类
            $classifyId = explode(",", input("classifyId"));
            foreach ($classifyId as $key => $value){
                $classifyId[$key] = "%".$value."%";
            }
            $map[] = ['ar_classifyId', 'like', $classifyId, 'OR'];
        }
        if(input('status') != null) $map[] = ['pr_status','=',input('status')];
        //查询
        $info = ArticleModel::getArticleList($map);
        //查询每个数据的分类
        foreach ($info as $key => $value){
            $where = [];
            $where[] = ["ac_id", "in", $value["ar_classifyId"]];
            $info[$key]["classify"] = ArticleClassify::getClassifyListAll($where);
        }
        //管理员权限
        $rules = ['Article/articleAdd', 'Article/articleEdit', 'Article/articleDel'];
        $check = AuthGroup::checkMethodArray(Session::get('userData'),$rules);

        View::assign('info',$info);
        View::assign('check',$check);
        return View::fetch('articleList');
    }
    /*
     * 新增文章
     */
    public function articleAdd(){
        if(Request::isPost()){
            $request = input();
            $map['ar_adminId'] = Session::get('userData.ad_id');
            $map['ar_title'] = $request['title'];
            $map['ar_classifyId'] = $request['classifyId'];
            $map['ar_subtitle'] = $request['subtitle'];
            $map['ar_image'] = $request['image'];
            $map['ar_content'] = $request['content'];
            $map['ar_status'] = $request['status'];
            $map['ar_sort'] = $request['sort'];
            $map['ar_time'] = strtotime($request['time']);
            //检查信息是否完整
            checkField($map);
            //新增信息
            $info = ArticleModel::create($map);
            if($info){
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'),'新增文章【'.$map['ar_title'].'】');

                $data = ['info'=>'新增成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，新增失败了','status'=>0];
            }
            return json($data);
        }
        //分类列表
        $classify = ArticleClassify::getClassifyListAll(["ac_status"=>1]);
        View::assign('classify',$classify);

        return View::fetch('articleAdd');
    }
    /*
     * 文章编辑
     */
    public function articleEdit(){
        $id = input('id');
        if(Request::isPost()){
            $request = input();
            $map['ar_id'] = $id;
            $map['ar_title'] = $request['title'];
            $map['ar_subtitle'] = $request['subtitle'];
            $map['ar_classifyId'] = $request['classifyId'];
            $map['ar_content'] = $request['content'];
            $map['ar_status'] = $request['status'];
            $map['ar_sort'] = $request['sort'];
            $map['ar_time'] = strtotime($request['time']);
            //更换封面删除旧封面
            if($request['oldImage'] != '' && $request['oldImage'] != $request['image']){
                unlink(Config::get('app.upload_url').$request['oldImage']);
                //新封面赋值
                $map['ar_image']  = $request['image'];
            }
            //检查信息是否完整
            checkField($map);
            //修改信息
            $info = ArticleModel::update($map, ["ar_id" => $id]);
            if($info){
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'),'编辑文章【'.$map['ar_title'].'】');

                $data = ['info'=>'编辑成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，信息没有改变','status'=>0];
            }
            return json($data);
        }
        $info = ArticleModel::getArticleInfo(["ar_id"=>$id]);
        //所有分类列表
        $classify = ArticleClassify::getClassifyListAll(["ac_status"=>1]);
        //文章目前所在分类id和名称
        $selected = [];
        $classifyIds = explode(",", $info["ar_classifyId"]);
        $selectedClassify = array_filter($classify->toArray(), function($v) use ($classifyIds){
            if(in_array($v["ac_id"], $classifyIds)){
                return $v;
            }
        });
        //重新组一个数组
        foreach ($selectedClassify as $key => $value){
            $selected["id"][$key] = $value["ac_id"];
            $selected["label"][$key] = $value["ac_title"];
        }
        $selected["id"] = implode(",", $selected["id"]);
        $selected["label"] = implode(",", $selected["label"]);

        View::assign('classify',$classify);
        View::assign('info',$info);
        View::assign('selected',$selected);
        return View::fetch('articleEdit');
    }
    /*
     * 文章封面上传
     */
    public function articleUpload(){
        $website = website();
        //限制2M
        $data = uploadFile('file',Config::get('app.article_url'), $website["sy_photoMaxSize"]);

        return json($data);
    }
    /*
     * 文章删除
     */
    public function articleDel(){
        //判断请求类型
        if(!Request::isPost()){
            $data = ['info'=>'请求类型不是这个哦，亲','status'=>0];
        }else{
            $id = input('id');
            //单个文章信息
            $article = ArticleModel::getArticleInfo(["ar_id"=>$id]);
            //删除文章
            $info = $article->delete();
            if($info){
                //删除封面
                unlink(Config::get('app.upload_url').$article['ar_image']);
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'), '删除文章【'.$article->ar_title.'】');

                $data = ['info'=>'删除成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，删除失败了','status'=>0];
            }
        }

        return json($data);
    }
//============================================【文章分类】=======================================
    /*
     * 文章分类列表
     */
    public function articleClassify(){
        //$map = [];
        //if(input('name')) $map[] = ['ac_title','like','%'.input('name').'%'];
        //if(input('status') != null) $map[] = ['ac_status','=',input('status')];
        $info = findChildLevel(ArticleClassify::getClassifyListAll()->toArray(), "ac_pid", "ac_id");
        //管理员权限
        $rules = ['Article/articleClassifyAdd', 'Article/articleClassifyEdit', 'Article/articleClassifyDel'];
        $check = AuthGroup::checkMethodArray(Session::get('userData'), $rules);

        View::assign('info',$info);
        View::assign('check',$check);
        return View::fetch('articleClassify');
    }
    /*
     * 文章分类增加
     */
    public function articleClassifyAdd(){
        $pid = input("pid");
        //判断请求类型
        if(Request::isPost()){
            $request = input();
            $map['ac_title']  = $request['title'];
            $map['ac_pid']  = $pid;
            $map['ac_status']  = $request['status'];
            $map['ac_type']  = $request['type'];
            //判断类型接收不同值
            if($request["type"] == 2){  //文章
                $map["ac_content"] = $request["content"];
                $map["ac_time"] = strtotime($request["time"]);
            }elseif ($request["type"] == 3){ //链接
                $map["ac_url"] = $request["url"];
            }
            //检查字段是否为空
            checkField($map);
            //新增信息
            $info = ArticleClassify::create($map);
            if($info){
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'),'新增文章分类【'.$map['ac_title'].'】');

                $data = ['info'=>'新增成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，信息没有改变','status'=>0];
            }
            return json($data);
        }
        //父id 信息
        if($pid > 0){
            $parent = ArticleClassify::getClassifyInfo(["ac_id"=>$pid])->ac_title;
        }else{
            $parent = "顶级";
        }
        View::assign('parent', $parent);
        return View::fetch('articleClassifyAdd');
    }
    /*
     * 文章分类编辑
     */
    public function articleClassifyEdit(){
        $id = input('id');
        $pid = input('pid');
        //判断请求类型
        if(Request::isPost()){
            $request = input();
            $map['ac_id']  = $id;
            $map['ac_title']  = $request['title'];
            $map['ac_pid']  = $request['pid'];
            $map['ac_status']  = $request['status'];
            $map['ac_type']  = $request['type'];
            //判断类型接收不同值
            if($request["type"] == 2){  //文章
                $map["ac_content"] = $request["content"];
                $map["ac_time"] = strtotime($request["time"]);
            }elseif ($request["type"] == 3){ //链接
                $map["ac_url"] = $request["url"];
            }
            //检查字段是否为空
            checkField($map);
            //修改信息
            $info = ArticleClassify::update($map, ["ac_id" => $id]);
            if($info){
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'),'编辑文章分类【'.$map['ac_title'].'】');

                $data = ['info'=>'编辑成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，信息没有改变','status'=>0];
            }
            return json($data);
        }
        $info = ArticleClassify::getClassifyInfo(["ac_id" => $id]);
        //父id 信息
        if($pid > 0){
            $parent = ArticleClassify::getClassifyInfo(["ac_id"=>$pid])->ac_title;
        }else{
            $parent = "顶级";
        }

        View::assign('parent', $parent);
        View::assign('info',$info);
        return View::fetch('articleClassifyEdit');
    }
    /*
     * 文章分类删除
     */
    public function articleClassifyDel(){
        //判断请求类型
        if(!Request::isPost()){
            $data = ['info'=>'请求类型不是这个哦，亲','status'=>0];
        }else{
            $id = input('id');
            //是否还有下级目录
            if(ArticleClassify::getClassifyListAll(["ac_pid"=>$id], 1) > 0){
                $data = ['info'=>'分类所属下还有下级分类，无法删除','status'=>0];
                return json($data);
            }
            //分类下是否还有文章
            if(ArticleModel::where('ar_classifyId', $id)->count('ar_id') > 0){
                $data = ['info'=>'分类所属下还有文章，无法删除','status'=>0];
                return json($data);
            }
            //查询信息
            $classify = ArticleClassify::getClassifyInfo(["ac_id"=>$id]);
            //删除信息
            $info = $classify->delete();
            if($info){
                //写入日志
                Log::logAdd(Session::get('userData.ad_id'),'删除文章分类【'.$classify->ac_title.'】');

                $data = ['info'=>'删除成功','status'=>1];
            }else{
                $data = ['info'=>'不好意思，删除失败了','status'=>0];
            }
        }

        return json($data);
    }
    /*
     * 获取所有分类组
     */
    public function getClassify(){

        $classify = getChildData(ArticleClassify::getClassifyListAll(["ac_status"=>1,"ac_type"=>1])->toArray(), "ac_pid", "ac_id", "ac_title");

        return json($classify);
    }
    /*
     * 获取分类组，并去除我点击的分类组，分类编辑时使用
     */
    public function getChildClassify(){
        //获取id
        $id = input("id");
        //获取所有的分类
        $array = ArticleClassify::getClassifyListAll(["ac_type"=>1])->toArray();
        //去除id = 编辑id的分类
        foreach ($array as $key => $value){
            if($value["ac_id"] == $id){
                unset($array[$key]);
            }
        }
        //递归列表，根据父id重组数据
        $classify = getChildData($array, "ac_pid", "ac_id", "ac_title");
        //新增顶级选项
        $key = count($classify) + 1;
        $data = [
            $key =>["id"=>0, "label"=>"顶级", "children"=>[]]
        ];
        $classify = array_merge($classify, $data);

        return json($classify);
    }
}